<script lang="ts" setup name="CouponSelect">
import { getIntDictOptions } from '@/utils/dict'
import { DICT_TYPE } from '@/enums/dictEnums'
import {
  discountFormat,
  remainedCountFormat,
  takeLimitCountFormat,
  validityTypeFormat
} from './helper'
import { dateFormatter } from '@/utils/dateUtil'
import { CouponApi, CouponTemplateType } from '@/api/mall/promotion/coupon'

defineProps<{
  multipleSelection: CouponTemplateType[]
}>()
const emit = defineEmits<{
  (e: 'update:multipleSelection', v: CouponTemplateType[])
}>()
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('选择优惠卷') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 字典表格数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: null,
  status: undefined,
  discountType: undefined,
  type: null,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 执行查询
    const data = await CouponApi.Template.page(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef?.value?.resetFields()
  handleQuery()
}

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  resetQuery()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const handleSelectionChange = (val: CouponTemplateType[]) => {
  emit('update:multipleSelection', val)
}

const submitForm = () => {
  dialogVisible.value = false
}
</script>

<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="65%">
    <!-- 搜索工作栏 -->
    <ContentWrap>
      <ElForm ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px" label-width="82px">
        <ElFormItem label="优惠券名称" prop="name">
          <ElInput v-model="queryParams.name" class="!w-240px" clearable placeholder="请输入优惠劵名" @keyup="handleQuery" />
        </ElFormItem>
        <ElFormItem label="优惠类型" prop="discountType">
          <ElSelect v-model="queryParams.discountType" class="!w-240px" clearable placeholder="请选择优惠券类型">
            <ElOption v-for="dict in getIntDictOptions(DICT_TYPE.PROMOTION_DISCOUNT_TYPE)" :key="dict.value" :label="dict.label" :value="dict.value" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="优惠券状态" prop="status">
          <ElSelect v-model="queryParams.status" class="!w-240px" clearable placeholder="请选择优惠券状态">
            <ElOption v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="创建时间" prop="createTime">
          <ElDatePicker v-model="queryParams.createTime" :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-240px" end-placeholder="结束日期" start-placeholder="开始日期" type="daterange" value-format="YYYY-MM-DD HH:mm:ss" />
        </ElFormItem>
        <ElFormItem>
          <ElButton @click="handleQuery">
            <SvgIcon class="mr-5px" icon="ep:search" />
            搜索
          </ElButton>
          <ElButton @click="resetQuery">
            <SvgIcon class="mr-5px" icon="ep:refresh" />
            重置
          </ElButton>
        </ElFormItem>
      </ElForm>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <ElTable v-loading="loading" :data="list" @selection-change="handleSelectionChange">
        <ElTableColumn type="selection" width="55" />
        <ElTableColumn label="优惠券名称" min-width="140" prop="name" />
        <ElTableColumn label="类型" min-width="80" prop="productScope">
          <template #default="scope">
            <DictTag :type="DICT_TYPE.PROMOTION_PRODUCT_SCOPE" :value="scope.row.productScope" />
          </template>
        </ElTableColumn>
        <ElTableColumn label="优惠" min-width="100" prop="discount">
          <template #default="scope">
            <DictTag :type="DICT_TYPE.PROMOTION_DISCOUNT_TYPE" :value="scope.row.discountType" />
            {{ discountFormat(scope.row) }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="领取方式" min-width="100" prop="takeType">
          <template #default="scope">
            <DictTag :type="DICT_TYPE.PROMOTION_COUPON_TAKE_TYPE" :value="scope.row.takeType" />
          </template>
        </ElTableColumn>
        <ElTableColumn :formatter="validityTypeFormat" align="center" label="使用时间" prop="validityType" width="185" />
        <ElTableColumn align="center" label="发放数量" prop="totalCount" />
        <ElTableColumn :formatter="remainedCountFormat" align="center" label="剩余数量" prop="totalCount" />
        <ElTableColumn :formatter="takeLimitCountFormat" align="center" label="领取上限" prop="takeLimitCount" />
        <ElTableColumn align="center" label="状态" prop="status">
          <template #default="scope">
            <DictTag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
          </template>
        </ElTableColumn>
        <ElTableColumn :formatter="dateFormatter" align="center" label="创建时间" prop="createTime" width="180" />
      </ElTable>
      <!-- 分页 -->
      <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo" :total="total" @pagination="getList" />
    </ContentWrap>
    <template #footer>
      <ElButton :disabled="formLoading" type="primary" @click="submitForm">确 定</ElButton>
      <ElButton @click="dialogVisible = false">取 消</ElButton>
    </template>
  </Dialog>
</template>
